package com.vastcom.jwt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@SpringBootApplication
@RestController
public class Application {

    @GetMapping("/api/admin")
    @PreAuthorize("hasAuthority('admin')")
    @ResponseBody
    public Object helloToAdmin(String userId){
        return "Hello World! You are ADMIN";
    }

    @GetMapping("/api/hello")
    @ResponseBody
    public Object hello(String userId){
        return "Hello World! You hava valid Token";
    }

    @PostMapping("/login")
    public Object login(HttpServletResponse response,
                        @RequestBody Account account) throws IOException{
        if (isValidPassword(account)){
            String jwt=JwtUtil.generateToken(account.username);
            return new HashMap<String,String>(){{
               put("token",jwt);
            }};
        }
        else {
            return new ResponseEntity(HttpStatus.UNAUTHORIZED);
        }
    }





    private boolean isValidPassword(Account ac){
        if("admin".equals(ac.username)&&"admin".equals(ac.password)
                ||"user".equals(ac.username)&&"user".equals(ac.password)){
            return true;

        }
        else
        {
            return false;
        }
    }


    public static class Account{
        public String username;
        public String password;
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }


}
